<template>
  <div class="supply-purchase">
    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <div class="search-header">
        <h2 class="page-title">物资统计</h2>
      </div>
      <div class="search-form">
        <div class="form-item">
          <label>货物名称</label>
          <input 
            v-model="searchForm.goodsName" 
            type="text" 
            placeholder="请输入货物名称"
            class="form-input"
          />
        </div>
        
        <div class="form-item">
          <label>材质</label>
          <div class="select-wrapper">
            <select 
              v-model="searchForm.materialid" 
              class="form-select"
            >
              <option value="">请选择材质</option>
              <option 
                v-for="material in materialOptions" 
                :key="material.id" 
                :value="material.id"
              >
                {{ material.materialName }}
              </option>
            </select>
        
          </div>
        </div>
        
        <div class="form-item">
          <label>产地</label>
          <input 
            v-model="searchForm.origin" 
            type="text" 
            placeholder="请输入产地"
            class="form-input"
          />
        </div>
        
        <div class="form-actions">
          <button @click="handleSearch" class="btn btn-primary">
            <i class="icon-search"></i>
            查询
          </button>
          <button @click="handleReset" class="btn btn-secondary">
            <i class="icon-refresh"></i>
            重置
          </button>
        </div>
      </div>
    </div>

    <!-- 数据表格区域 -->
    <div class="table-section">
      <table class="data-table">
        <thead>
          <tr>
            <th>货物名称</th>
            <th>类型</th>
            <th>材质</th>
            <th>规格</th>
            <th>产地</th>
            <th>结余数量</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading">
            <td colspan="6" class="loading-cell">
              <div class="loading-spinner">加载中...</div>
            </td>
          </tr>
          <tr v-else-if="tableData.length === 0">
            <td colspan="6" class="empty-cell">
              暂无数据
            </td>
          </tr>
          <tr v-else v-for="(item, index) in tableData" :key="item.id">
            <td>{{ item.goodsName || '-' }}</td>
            <td>{{ item.typeName || '-' }}</td>
            <td>{{ item.materialName || '-' }}</td>
            <td>{{ item.size || '-' }}</td>
            <td>{{ item.origin || '-' }}</td>
            <td>{{ item.endingBalanceQuantity || 0 }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <div class="pagination-info">
        共{{ totalPages }}页/{{ totalCount }}条数据
      </div>
      <div class="pagination-controls">
        <button 
          @click="goToPage(currentPage - 1)" 
          :disabled="currentPage === 1"
          class="btn-pagination"
        >
          &lt;
        </button>
        
        <button 
          v-for="page in visiblePages" 
          :key="page"
          @click="goToPage(page)"
          :class="['btn-pagination', { active: page === currentPage }]"
        >
          {{ page }}
        </button>
        
        <button 
          v-if="showEllipsis"
          class="btn-pagination disabled"
        >
          ...
        </button>
        
        <button 
          v-if="showLastPage"
          @click="goToPage(totalPages)"
          :class="['btn-pagination', { active: currentPage === totalPages }]"
        >
          {{ totalPages }}
        </button>
        
        <button 
          @click="goToPage(currentPage + 1)" 
          :disabled="currentPage === totalPages"
          class="btn-pagination"
        >
          &gt;
        </button>
      </div>
      
      <div class="pagination-jump">
        <span>跳至</span>
        <input 
          v-model="jumpToPage" 
          type="number" 
          min="1" 
          :max="totalPages"
          @keyup.enter="handleJumpToPage"
          class="jump-input"
        />
        <span>页</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { materialApi } from '@/api'

// 定义接口类型
interface MaterialStatisticsItem {
  id: number
  swNo: string
  goodsName: string | null
  typeId: number
  materialid: number
  size: string
  origin: string
  endingBalanceQuantity: number
  materialName: string
  typeName: string
}

interface MaterialOption {
  id: number
  materialName: string
}

interface ApiResponse {
  items: MaterialStatisticsItem[]
  totalCount: number
  pageIndex: number
  pageSize: number
  totalPages: number
}

interface MaterialApiResponse {
  code: number
  message: string
  data: MaterialOption[]
}

// 搜索表单数据
const searchForm = reactive({
  goodsName: '',
  materialid: '',
  origin: ''
})

// 材质选项数据
const materialOptions = ref<MaterialOption[]>([])

// 表格数据
const tableData = ref<MaterialStatisticsItem[]>([])
const loading = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const totalPages = ref(0)
const totalCount = ref(0)
const jumpToPage = ref(1)

// 计算属性
const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, start + 4)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  return pages
})

const showEllipsis = computed(() => {
  return totalPages.value > 5 && currentPage.value < totalPages.value - 2
})

const showLastPage = computed(() => {
  return totalPages.value > 5 && currentPage.value < totalPages.value - 2
})

// 获取材质选项数据
const fetchMaterialOptions = async () => {
  try {
    console.log('开始获取材质数据...')
    console.log('使用的API方法:', materialApi.getMaterials)
    const response = await materialApi.getMaterials()
    console.log('材质数据API响应:', response)

    if (response.code === 200) {
      materialOptions.value = response.data
      console.log('材质数据加载成功:', response.data)
    } else {
      throw new Error(response.message || '获取材质数据失败')
    }
  } catch (error) {
    console.error('获取材质数据出错:', error)
    // 如果API调用失败，使用模拟数据
    materialOptions.value = [
      { id: 1, materialName: "金属" },
      { id: 2, materialName: "橡胶" },
      { id: 3, materialName: "塑料" },
      { id: 4, materialName: "液体" },
      { id: 5, materialName: "纸质" }
    ]
  }
}

// 获取物资统计数据
const fetchMaterialStatistics = async () => {
  try {
    loading.value = true
    
    // 构建查询参数
    const params: any = {
      pageIndex: currentPage.value,
      pageSize: pageSize.value
    }
    
    // 添加搜索条件（如果后端支持的话）
    if (searchForm.goodsName && searchForm.goodsName.trim()) {
      params.goodsName = searchForm.goodsName.trim()
    }
    if (searchForm.materialid && searchForm.materialid !== '') {
      params.materialid = parseInt(searchForm.materialid)
    }
    if (searchForm.origin && searchForm.origin.trim()) {
      params.origin = searchForm.origin.trim()
    }

    // 调用封装的API方法
    console.log('请求参数:', params)
    console.log('使用的API方法:', materialApi.getMaterialStatistics)
    const response = await materialApi.getMaterialStatistics(params)
    console.log('API响应:', response)

    if (response.code === 200) {
      const data = response.data
      console.log('处理的数据:', data)
      
      let filteredData: MaterialStatisticsItem[] = []
      
      // 检查 data 是否是数组
      if (Array.isArray(data)) {
        filteredData = data
      } else {
        // 如果 data 是对象，尝试访问 items 属性
        filteredData = data.items || []
      }
      
      // 前端过滤（如果后端不支持查询参数）
      if (searchForm.goodsName && searchForm.goodsName.trim()) {
        filteredData = filteredData.filter(item => 
          item.goodsName && item.goodsName.includes(searchForm.goodsName.trim())
        )
      }
      
      if (searchForm.materialid && searchForm.materialid !== '') {
        const materialId = parseInt(searchForm.materialid)
        filteredData = filteredData.filter(item => item.materialid === materialId)
      }
      
      if (searchForm.origin && searchForm.origin.trim()) {
        filteredData = filteredData.filter(item => 
          item.origin && item.origin.includes(searchForm.origin.trim())
        )
      }
      
      // 分页处理
      const startIndex = (currentPage.value - 1) * pageSize.value
      const endIndex = startIndex + pageSize.value
      const paginatedData = filteredData.slice(startIndex, endIndex)
      
      tableData.value = paginatedData
      totalCount.value = filteredData.length
      totalPages.value = Math.ceil(filteredData.length / pageSize.value)
      
      console.log('过滤后的数据:', filteredData)
      console.log('分页后的数据:', paginatedData)
      console.log('总记录数:', totalCount.value)
      console.log('总页数:', totalPages.value)
    } else {
      throw new Error(response.message || '获取数据失败')
    }
    
  } catch (error) {
    console.error('获取数据出错:', error)
    // 如果API调用失败，使用模拟数据
    const mockData: MaterialStatisticsItem[] = [
      {
        id: 3,
        swNo: "SW202509190002",
        goodsName: null,
        typeId: 1,
        materialid: 5,
        size: "2",
        origin: "中国-上海市",
        endingBalanceQuantity: 1,
        materialName: "纸质",
        typeName: "车辆用品"
      },
      {
        id: 4,
        swNo: "SW202509190003",
        goodsName: "轮胎",
        typeId: 1,
        materialid: 2,
        size: "1200R20",
        origin: "中国-上海市",
        endingBalanceQuantity: 130,
        materialName: "橡胶",
        typeName: "车辆用品"
      },
      {
        id: 5,
        swNo: "SW202509190004",
        goodsName: "轮胎",
        typeId: 1,
        materialid: 2,
        size: "1200R20",
        origin: "中国-上海市",
        endingBalanceQuantity: 130,
        materialName: "橡胶",
        typeName: "车辆用品"
      },
      {
        id: 6,
        swNo: "SW202509190005",
        goodsName: "轮胎",
        typeId: 1,
        materialid: 2,
        size: "1200R20",
        origin: "中国-上海市",
        endingBalanceQuantity: 130,
        materialName: "橡胶",
        typeName: "车辆用品"
      },
      {
        id: 7,
        swNo: "SW202509190006",
        goodsName: "轮胎",
        typeId: 1,
        materialid: 2,
        size: "1200R20",
        origin: "中国-上海市",
        endingBalanceQuantity: 130,
        materialName: "橡胶",
        typeName: "车辆用品"
      },
      {
        id: 8,
        swNo: "SW202509190007",
        goodsName: "轮胎",
        typeId: 1,
        materialid: 2,
        size: "1200R20",
        origin: "中国-上海市",
        endingBalanceQuantity: 130,
        materialName: "橡胶",
        typeName: "车辆用品"
      }
    ]
    
    tableData.value = mockData
    totalCount.value = 100
    totalPages.value = 10
    
    alert('获取数据出错，已显示模拟数据')
  } finally {
    loading.value = false
  }
}

// 方法
const handleSearch = () => {
  console.log('执行搜索，搜索条件:', searchForm)
  currentPage.value = 1
  fetchMaterialStatistics()
}

const handleReset = () => {
  console.log('执行重置')
  searchForm.goodsName = ''
  searchForm.materialid = ''
  searchForm.origin = ''
  currentPage.value = 1
  fetchMaterialStatistics()
}

const goToPage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    jumpToPage.value = page
    fetchMaterialStatistics()
  }
}

const handleJumpToPage = () => {
  goToPage(jumpToPage.value)
}

onMounted(() => {
  // 同时获取材质选项和统计数据
  fetchMaterialOptions()
  fetchMaterialStatistics()
})
</script>

<style scoped>
.supply-purchase {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 搜索区域样式 */
.search-section {
  background: white;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.search-header {
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
  color: #28a745;
}

.search-form {
  display: flex;
  gap: 20px;
  align-items: end;
  flex-wrap: wrap;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 200px;
}

.form-item label {
  font-weight: bold;
  color: #333;
  font-size: 14px;
}

.form-input, .form-select {
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
  background: white;
}

.form-input:focus, .form-select:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0,123,255,0.25);
}

.select-wrapper {
  position: relative;
}

.dropdown-icon {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #666;
  font-size: 12px;
  pointer-events: none;
}

.form-actions {
  display: flex;
  gap: 10px;
}

/* 按钮样式 */
.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 5px;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-primary:hover {
  background: #0056b3;
  transform: translateY(-1px);
}

.btn-secondary {
  background: white;
  color: #333;
  border: 1px solid #ddd;
}

.btn-secondary:hover {
  background: #f8f9fa;
  border-color: #007bff;
}

/* 表格样式 */
.table-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px 8px;
  text-align: left;
  border-bottom: 1px solid #eee;
  font-size: 14px;
}

.data-table th {
  background: #f8f9fa;
  font-weight: bold;
  color: #333;
  position: sticky;
  top: 0;
}

.data-table tbody tr:hover {
  background: #f8f9fa;
}

/* 分页样式 */
.pagination-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination-info {
  color: #666;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  gap: 5px;
  align-items: center;
}

.btn-pagination {
  padding: 8px 12px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-pagination:hover:not(.disabled) {
  background: #f8f9fa;
}

.btn-pagination.active {
  background: #28a745;
  color: white;
  border-color: #28a745;
}

.btn-pagination:disabled,
.btn-pagination.disabled {
  background: #f8f9fa;
  color: #6c757d;
  cursor: not-allowed;
}

.pagination-jump {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.jump-input {
  width: 60px;
  padding: 6px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  text-align: center;
}

/* 加载状态样式 */
.loading-cell, .empty-cell {
  text-align: center;
  padding: 40px;
  color: #666;
  font-size: 16px;
}

.loading-spinner {
  display: inline-block;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 图标样式 */
.icon-search::before {
  content: "🔍";
}

.icon-refresh::before {
  content: "";
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .form-item {
    min-width: auto;
  }
  
  .pagination-section {
    flex-direction: column;
    gap: 15px;
  }
}

@media (max-width: 768px) {
  .supply-purchase {
    padding: 10px;
  }
  
  .data-table {
    font-size: 12px;
  }
  
  .data-table th,
  .data-table td {
    padding: 8px 4px;
  }
}
</style>
